import React, { useEffect, useState, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Select, Typography, InputNumber, Input, Row, Col, Switch } from 'antd';
import { createGlobalStyle } from 'styled-components';
import { selectVideoBackgroundFillingById, updateVideoProperties } from '@/store/videosSlice';
import { selectStickerById, updateStickerProperties } from '@/store/stickersSlice';
import type { RootState } from '@/store';
import type { BackgroundFilling } from '@/store/videoTypes';

const { Title, Text } = Typography;
const { Option } = Select;

// 添加蒙层样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* 自定义滚动条样式 */
    .config-background-filling-scroll::-webkit-scrollbar {
        width: 3px; background: transparent;
    }
    .config-background-filling-scroll::-webkit-scrollbar-thumb {
        background: #715BB8; border-radius: 4px;
    }
    /* 表单标签 */
    .ant-form-item-label > label {
        color: #FFFFFF !important;
    }
    /* 输入/选择控件 */
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus,
    .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }
    /* 开关样式 */
    .ant-switch { background-color: #555555 !important; }
    .ant-switch-checked { background-color: #715BB8 !important; }
    /* 表单蒙层 */
    .form-overlay {
        position: relative;
    }
    .form-overlay::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.4);
        pointer-events: none;
        z-index: 1;
    }
`;

interface ConfigBackgroundFillingFormProps {
    mediaId: string;
}

// 剪映风格的模糊程度选项
const blurOptions = [
    { value: 0.0625, label: '轻微模糊' },
    { value: 0.375, label: '中度模糊' },
    { value: 0.75, label: '高模糊' },
    { value: 1.0, label: '最高模糊' },
];

const ConfigBackgroundFillingForm: React.FC<ConfigBackgroundFillingFormProps> = ({ mediaId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();

    // 判断是否为贴纸
    const isSticker = mediaId?.includes('sticker') || false;

    // 根据是否为贴纸选择不同的selector
    const mediaBackgroundFilling = useSelector((state: RootState) => {
        if (!mediaId) return null;
        if (isSticker) {
            const sticker = selectStickerById(state, mediaId);
            return sticker?.background_filling || null;
        }
        return selectVideoBackgroundFillingById(state, mediaId);
    });

    const [activeFillType, setActiveFillType] = useState<'blur' | 'color' | null>(null);
    const [isEnabled, setIsEnabled] = useState<boolean>(false);

    // 初始化表单和启用状态
    useEffect(() => {
        // 根据background_filling对象的fill_type设置启用状态
        // 当fill_type是none时，按钮为不勾选状态；否则为勾选状态
        const isFillTypeNone = mediaBackgroundFilling && mediaBackgroundFilling.fill_type === 'none';
        const shouldBeEnabled = mediaBackgroundFilling && mediaBackgroundFilling.fill_type && mediaBackgroundFilling.fill_type !== 'none';

        setIsEnabled(shouldBeEnabled ?? false);

        if (mediaBackgroundFilling) {
            setActiveFillType(mediaBackgroundFilling.fill_type === 'none' ? null : mediaBackgroundFilling.fill_type);
            form.setFieldsValue({
                fill_type: mediaBackgroundFilling.fill_type === 'none' ? 'blur' : mediaBackgroundFilling.fill_type, // 默认显示模糊选项
                blur: mediaBackgroundFilling.blur,
                color: mediaBackgroundFilling.color,
            });
        } else {
            // 设置默认值
            setActiveFillType('blur');
            form.setFieldsValue({
                fill_type: 'blur',
                blur: 0.0625,
                color: '#000000FF',
            });
        }
    }, [mediaBackgroundFilling, form]);

    // 处理启用状态变化
    const handleEnableChange = (checked: boolean) => {
        setIsEnabled(checked);

        if (!mediaId) return;

        if (checked) {
            // 如果启用，使用当前表单值
            const formValues = form.getFieldsValue();
            const backgroundFillingUpdates: BackgroundFilling = {
                fill_type: formValues.fill_type,
            };

            if (formValues.fill_type === 'blur') {
                backgroundFillingUpdates.blur = formValues.blur || 0.0625;
            } else if (formValues.fill_type === 'color') {
                backgroundFillingUpdates.color = formValues.color || '#000000FF';
            }

            // 更新到redux
            if (isSticker) {
                dispatch(
                    updateStickerProperties({
                        id: mediaId,
                        updates: {
                            background_filling: backgroundFillingUpdates,
                        },
                    })
                );
            } else {
                dispatch(
                    updateVideoProperties({
                        id: mediaId,
                        updates: {
                            background_filling: backgroundFillingUpdates,
                        },
                    })
                );
            }
        } else {
            // 如果禁用，设置fill_type为none
            const backgroundFillingUpdates: BackgroundFilling = {
                fill_type: 'none',
            };

            if (isSticker) {
                dispatch(
                    updateStickerProperties({
                        id: mediaId,
                        updates: {
                            background_filling: backgroundFillingUpdates,
                        },
                    })
                );
            } else {
                dispatch(
                    updateVideoProperties({
                        id: mediaId,
                        updates: {
                            background_filling: backgroundFillingUpdates,
                        },
                    })
                );
            }
        }
    };

    const handleFormChange = useCallback(
        (changedValues: any, allValues: any) => {
            if (!mediaId || !isEnabled) return;

            if ('fill_type' in changedValues) {
                setActiveFillType(allValues.fill_type as 'blur' | 'color');
            }

            // 构建背景填充更新对象
            const backgroundFillingUpdates: BackgroundFilling = {
                fill_type: allValues.fill_type,
            };

            // 根据填充类型添加相应的属性
            if (allValues.fill_type === 'blur') {
                backgroundFillingUpdates.blur = allValues.blur || 0.0625;
            } else if (allValues.fill_type === 'color') {
                backgroundFillingUpdates.color = allValues.color || '#000000FF';
            }

            // 根据是否为贴纸调用不同的action
            if (isSticker) {
                dispatch(
                    updateStickerProperties({
                        id: mediaId,
                        updates: {
                            background_filling: backgroundFillingUpdates,
                        },
                    })
                );
            } else {
                dispatch(
                    updateVideoProperties({
                        id: mediaId,
                        updates: {
                            background_filling: backgroundFillingUpdates,
                        },
                    })
                );
            }
        },
        [mediaId, dispatch, isSticker, isEnabled]
    );

    if (!mediaId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何素材
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            <div
                className="config-background-filling-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    背景填充
                </Title>

                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '24px',
                        border: '1px solid #555555',
                    }}
                >
                    <div
                        style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                        }}
                    >
                        <Text style={{ color: '#FFFFFF' }}>
                            {mediaBackgroundFilling ? (mediaBackgroundFilling.fill_type === 'none' ? '类型: 无' : `类型: ${mediaBackgroundFilling.fill_type === 'blur' ? '模糊' : '颜色'}`) : '背景填充未启用'}
                        </Text>
                        <Switch checked={isEnabled} onChange={handleEnableChange} checkedChildren="启用" unCheckedChildren="禁用" />
                    </div>
                </div>

                <div className={isEnabled ? '' : 'form-overlay'}>
                    <Form form={form} layout="vertical" onValuesChange={handleFormChange} disabled={!isEnabled}>
                        <Form.Item name="fill_type" label="填充类型">
                            <Select placeholder="请选择填充类型" style={{ width: '98%' }}>
                                <Option value="blur">模糊</Option>
                                <Option value="color">颜色</Option>
                            </Select>
                        </Form.Item>

                        {/* 模糊程度配置 */}
                        {activeFillType === 'blur' && (
                            <div>
                                <Title
                                    level={5}
                                    style={{
                                        marginTop: 16,
                                        marginBottom: 8,
                                        color: '#FFFFFF',
                                    }}
                                >
                                    模糊设置
                                </Title>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <Form.Item name="blur" label="模糊程度">
                                            <Select placeholder="请选择模糊程度" style={{ width: '90%' }}>
                                                {blurOptions.map((option) => (
                                                    <Option key={option.value} value={option.value}>
                                                        {option.label}
                                                    </Option>
                                                ))}
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item name="blur" label="精确值">
                                            <InputNumber min={0.0} max={1.0} step={0.01} style={{ width: '90%' }} />
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </div>
                        )}

                        {/* 颜色填充配置 */}
                        {activeFillType === 'color' && (
                            <div>
                                <Title
                                    level={5}
                                    style={{
                                        marginTop: 16,
                                        marginBottom: 8,
                                        color: '#FFFFFF',
                                    }}
                                >
                                    颜色设置
                                </Title>
                                <Row gutter={16}>
                                    <Col span={24}>
                                        <Form.Item name="color" label="填充颜色 (格式: #RRGGBBAA)">
                                            <Input placeholder="请输入16进制颜色值，如#000000FF" style={{ width: '98%' }} />
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </div>
                        )}
                    </Form>
                </div>
            </div>
        </>
    );
};
export default ConfigBackgroundFillingForm;
